package com.example.demo.framework;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.example.demo.model.UserInfo;
import com.example.demo.repository.UserRepository;

@Component
public class LoginInterceptor implements HandlerInterceptor {

	Logger log = LoggerFactory.getLogger(LoginInterceptor.class);

	@Autowired
	private UserRepository userRepository;

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		String token=request.getParameter("token");
		String url = request.getRequestURL().toString();
		String method = request.getMethod();
		String uri = request.getRequestURI();
		String queryString = request.getQueryString();
		log.info(String.format("请求参数,toekn:%s, url: %s, method: %s, uri: %s, params: %s",token, url, method, uri, queryString));
		UserInfo user=userRepository.getByToken(token);
		if(user==null){
			throw new BusinessException(ErrorCode.ERROR_10003);
		}
		
		request.setAttribute("user", user);
		return true;
	}

}
